package com.zyz.framework.advice;


import com.zyz.common.annotation.FileData;
import com.zyz.common.exception.base.BaseException;
import com.zyz.common.utils.WebKit;
import com.zyz.common.utils.html.HtmlKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 文件路径请求处理
 * 
 * @author zyz
 * @date 2021年3月2日
 */
@ControllerAdvice
public class FileDataRequestBodyAdvice implements RequestBodyAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(FileDataRequestBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType) {

        if (body == null) {
            return body;
        }

        final String basePath = WebKit.getBasePath();

        try {
            BodyAdviceKit.resetSimpleObject(body, FileData.class, new BodyAdvice() {
                @Override
                public Object getAdviceFieldValue(Object fieldValue) {
                    return HtmlKit.getDbFilePath(String.valueOf(fieldValue), basePath);
                }
            });
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new BaseException("数据解析异常");
        }

        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
            Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

}